//
// FileDownListViewController.m
// LBXDownLoad
//
// Created by lbxia on 2021/4/25
//
//
    

#import "FileDownListViewController.h"
#import <Masonry.h>
#import "LBXDownLoadManager.h"
#import "FileDowningTableViewCell.h"
#import <LBXAlertAction.h>
#import "FileDownedListViewController.h"

@interface FileDownListViewController ()<UITableViewDelegate,UITableViewDataSource,LBXDownLoadManagerProtocol>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) BOOL editing;
@end

@implementation FileDownListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    NSArray* arrayDownURLS = @[
        @"https://www.imagomat.de/testimages/1.tiff",
        @"https://www.apple.com/105/media/cn/iphone-x/2017/01df5b43-28e4-4848-bf20-490c34a926a7/films/feature/iphone-x-feature-cn-20170912_1280x720h.mp4",
        @"https://www.apple.com/105/media/us/iphone-12/2020/7f5b7de7-9f8c-41eb-bf3b-f294773108e6/films/product/iphone-12-product-tpl-us-2020_16x9.m3u8",
        @"https://www.apple.com.cn/imac-24/images/overview/colors_hero_fallback__co1mroy32piu_large.jpg",
        @"https://www.apple.com.cn/105/media/cn/iphone-12-pro/2020/e70ffbd8-50f1-40f3-ac36-0f03a15ac314/films/product/iphone-12-pro-product-tpl-cn-2020_16x9.m3u8",
        @"https://www.apple.com.cn/105/media/us/ipad-pro/2021/08087f4b-7539-4b1e-ae8a-adc18f4242ae/anim/cameras/large.mp4"
    ];
    
    for (int i = 0; i < arrayDownURLS.count; i++) {
        
        LBXDownLoadItem *item = [[LBXDownLoadItem alloc]init];
        item.remoteURL = arrayDownURLS[i];
        [[LBXDownLoadManager sharedManager]addItem:item];
    }
    [LBXDownLoadManager sharedManager].delegate = self;
    
    [self tableView];
    
    NSLog(@"%@",[LBXDownLoadManager sharedManager].session);
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"功能" style:UIBarButtonItemStyleDone target:self action:@selector(funList)];
}

- (void)funList
{
    [LBXAlertAction showActionSheetWithTitle:@"功能" message:@"测试功能" cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitle:@[@"编辑",@"已下载列表"] chooseBlock:^(NSInteger buttonIdx) {
        switch (buttonIdx) {
            case 1:
            {
                self.editing = !self.editing;
                [self.tableView reloadData];
            }
                break;
            case 2:
            {
                FileDownedListViewController *vc = [[FileDownedListViewController alloc]init];
                [self.navigationController pushViewController:vc animated:YES];
            }
                break;
                
            default:
                break;
        }
    }];
}

- (UITableView*)tableView
{
    if ( !_tableView )
    {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView setSeparatorInset:UIEdgeInsetsZero];
        [self.view addSubview:_tableView];
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.equalTo(self.view);
            make.bottom.equalTo(self.view).with.offset(-44);
        }];
        
        _tableView.tableFooterView = [[UIView alloc]init];
    }
    return _tableView;
}

#pragma mark- LBXDownLoad Delegate
- (void)LBXDownLoadSucess:(LBXDownLoadItem*)item
{
    [self refreshUI];
}


//自定义请求,自定义设置相关协议头等等
//- (NSURLRequest*)LBXCustomNSURLRequest:(LBXDownLoadItem*)item;

//硬盘空间不足，所有下载暂停
- (void)LBXDownLoadDiskSpaceNotAvailable
{
    
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [LBXDownLoadManager sharedManager].downLoadItems.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 95;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    //不可以复用cell，否则导致进度可能显示在2个地方,另外tableView显示不到的地方，需要另外监听处理
    FileDowningTableViewCell *cell = [FileDowningTableViewCell instanceWithEditing:_editing];
    
    
    if (indexPath.row > [LBXDownLoadManager sharedManager].downLoadItems.count-1) {
        NSLog(@"数据不同步");
        return cell;
    }
    
    if (cell.item) {
        //之前的block设置为空，否则由于cell复用，可能导致2中状态，cell数据源就会有2个
        cell.item.onStatusChanged = nil;
        cell.item.onProgressChanged = nil;
    }
    
    LBXDownLoadItem *item = [LBXDownLoadManager sharedManager].downLoadItems[indexPath.row];
    cell.item = item;
        
    item.onProgressChanged = ^(LBXDownLoadItem *item) {
        cell.item = item;
    };
    
    __weak typeof(self) weakSelf = self;
    item.onStatusChanged = ^(LBXDownLoadItem *item) {
        cell.item = item;
        
    };
    
    if (_editing) {
//        cell.selectImg.image = [UIImage imageNamed:item.yq_selected?@"选择":@"未选择"];
    }
    
    return cell;
}

- (void)refreshUI
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self.tableView reloadData];
    });
}

#pragma mark- 点击cell

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    LBXDownLoadItem* item = [LBXDownLoadManager sharedManager].downLoadItems[indexPath.row];

    if (self.editing) {
        
//        item.yq_selected = !item.yq_selected;
        FileDowningTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//        cell.selectImg.image = [UIImage imageNamed:item.yq_selected?@"选择":@"未选择"];

//        [self checkAllSelectionViewStatus];
//
//        [self refreshUI];
        
        return;
    }
    
    NSInteger status = item.status;
    
    if ( status == LBXDownloadStatus_Completed ) {
        
        [[LBXDownLoadManager sharedManager]clearFinishItem];
        
        [self.tableView reloadData];
    }
    else
    {
        if (item.status == LBXDownloadStatus_Readying) {
            item.status = LBXDownloadStatus_Suspended;
        }
        else if ( item.status == LBXDownloadStatus_Running  )
        {
            [[LBXDownLoadManager sharedManager]suspendWithItem:item];
            
//            item.priorityLevel = 0;
//            
//            //自动下一个
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [[LBXDownLoadManager sharedManager]autoDownNextItem];
//            });
        }
        else
        {
            [[LBXDownLoadManager sharedManager]startWithItem:item];
        }
        
        //底部按钮文字修改
//        [self refreshUI];
        
//        [self addCoverView];
        
        //延时1s才能点击
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//              [self clearCoverView];
        });
    }
}

#pragma mark - 侧滑删除
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        
        LBXDownLoadItem* item = [LBXDownLoadManager sharedManager].downLoadItems[indexPath.row];

        [[LBXDownLoadManager sharedManager]cancelWithItem:item];
        
        [self.tableView reloadData];
       
    }
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

@end
